package com.ywj.chatroom.multiroom.server.handler;

import com.ywj.chatroom.multiroom.message.GroupCreateRequestMessage;
import com.ywj.chatroom.multiroom.message.GroupCreateResponseMessage;
import com.ywj.chatroom.multiroom.server.session.Group;
import com.ywj.chatroom.multiroom.server.session.GroupSession;
import com.ywj.chatroom.multiroom.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

//import java.nio.channels.Channel;
import java.util.List;
import java.util.Set;

/**
 * 创建群消息处理器
 * 1.获取群聊名字    2.获取到要拉进去的人
 * 3.创建一个Group，create方法进行存储到map了
 * 4.给拉进群的人发送消息，通知他们被拉进群了
 */
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        Set<String> members = msg.getMembers();

        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.createGroup(groupName, members);
        if(group == null){
            //向用户发送拉入群消息
            List<Channel> channels = groupSession.getMembersChannel(groupName);
            for(Channel channel : channels){
                if(!channel.equals(ctx.channel())){
                    channel.writeAndFlush(new GroupCreateResponseMessage(true, "您已被拉入群聊" + groupName));
                }
            }
            ctx.writeAndFlush(new GroupCreateResponseMessage(true, "创建群聊" + groupName +"成功"));
        }else{
            ctx.writeAndFlush(new GroupCreateResponseMessage(false, "群已经存在，无法重复创建"));
        }

    }
}
